﻿package
{
	import flash.display.Graphics;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.*;
	import flash.net.URLRequest;
	import fl.controls.ColorPicker;
	import fl.events.ColorPickerEvent;
	import treatBehavior.*;
	import adapter.PointToDistance;
	
	public class RoadDIY extends Sprite
	{
//-----------------------------------------------------------------------------------------------PUBLIC------------------------------------
													//================ Properties ===============
													//================ Constructor ==============
		public function RoadDIY():void
		{
			initSpr();//初始化容器，以及他们之间的层级关系；
			initBack();//初始化背景；
			initVar();//初始化变量；
			initListener();//注册侦听函数；
		}																										
													//================ Public Methods ===========
//-----------------------------------------------------------------------------------------------PRIVATE-----------------------------------
													
													//================ Properties ===============
		private var drawSpr:Sprite;
		private var dataSpr:Sprite;
		private var drawBoard:Sprite;
		private var drawCtrBar:Sprite;
		private var backLoader:Loader;
		private var drawRoad:DrawCurve;
		private var resultCurve:Sprite;
		private var ballSpr:Sprite;
		
		private var previewArr:Array;//处理过的路径预览数据；
		private var resultArr:Array;//最后显示出来，并最后使用的数据；
		private var ballD:Number;//球直径
		private var divideCount:int;//分割数
		private var ballList:Array;//球的运动演示时，存储球的引用的数组；
		
		private var oriColor:int;//绘图曲线颜色；
		private var previewColor:int;//计算得到的曲线颜色
		
		private var imgWidth:Number;
		private var imgHeight:Number;
													//================ Private Methods ==========
		private function initSpr():void
		{
			stage.scaleMode="noScale";
			drawSpr=new Sprite();
			dataSpr=new Sprite();
			drawBoard=new Sprite();
			drawCtrBar=new Sprite();
			backLoader=new Loader();
			resultCurve=new Sprite();
			ballSpr=new Sprite();
			
			stage.addChild(drawSpr);
			drawSpr.visible=true;
			stage.addChild(dataSpr);
			dataSpr.visible=false;
			
			drawSpr.addChild(drawBoard);
			drawSpr.addChild(drawCtrBar);
			
			drawBoard.addChild(backLoader);
			drawBoard.addChild(ballSpr);
			drawBoard.addChild(resultCurve);
		
			drawCtrBar.addChild(__ballDLab);
			drawCtrBar.addChild(__divideLab);
			drawCtrBar.addChild(__bgLinkLab);
			drawCtrBar.addChild(__ballD);
			drawCtrBar.addChild(__divideCount);
			drawCtrBar.addChild(__bgLink);
			drawCtrBar.addChild(__oriColorLab);
			drawCtrBar.addChild(__previewColorLab);
			drawCtrBar.addChild(__oriColorCP);
			drawCtrBar.addChild(__previewColorCP);
			drawCtrBar.addChild(__startButt);
			drawCtrBar.addChild(__previewButt);
			drawCtrBar.addChild(__ballMoveButt);
			drawCtrBar.addChild(__getButt);
			
			drawCtrBar.addChild(__imgWidthLab);
			drawCtrBar.addChild(__imgHeightLab);
			drawCtrBar.addChild(__imgWidth);
			drawCtrBar.addChild(__imgHeight);
			drawCtrBar.addChild(__enterButt);
			
			dataSpr.addChild(__resultText);
			dataSpr.addChild(__backButt);
			
			
		}
		private function initBack():void
		{
			var gr:Graphics=drawBoard.graphics;
			gr.lineStyle(2);
			gr.beginFill(0X000055,.5);
			gr.drawRect(0,0,stage.stageWidth,stage.stageHeight-40);
			gr.endFill();	
		}
		private function initVar():void
		{
			previewArr=new Array();
			resultArr=new Array();
			ballList=new Array();
			oriColor=0X55555;
			previewColor=0X66FFFF;
			imgWidth = 1000;
			imgHeight=760;
		}
		private function initListener():void
		{
			__startButt.addEventListener(MouseEvent.CLICK,startHandler);
			__previewButt.addEventListener(MouseEvent.CLICK,previewHandler);
			__ballMoveButt.addEventListener(MouseEvent.CLICK,moveHandler);
			__getButt.addEventListener(MouseEvent.CLICK,getHandler);
			__backButt.addEventListener(MouseEvent.CLICK,backHandler);
			__enterButt.addEventListener(MouseEvent.CLICK,enterHandler);
			
			__oriColorCP.addEventListener(ColorPickerEvent.CHANGE,oriChangeHandler);
			__previewColorCP.addEventListener(ColorPickerEvent.CHANGE,previewChangeHandler);
		}
		private function treatData():Array
		{
			ballD=Number(__ballD.text);
			if(ballD<=1e-6)
			{
				trace("please input the right number of the ball diameter!!!\n");
				ballD=26;
			}
			divideCount=int(__divideCount.text);
			if(divideCount<1e-6)
			{
				trace("please input the right number of the divideNumber!!!\n");
				divideCount=26;
			}
			if(drawRoad.getRoadArr()!=null)
			{
				var treatRoad:TreatRoadArr=new TreatRoadArr(drawRoad);
				var bh:ITreatBehavior=new BezierBehavior(drawRoad.getRoadArr());
				treatRoad.getTreatBehavior(bh);
				previewArr=treatRoad.getRoadArr();
				bh=new ResortBehavior(previewArr,ballD,divideCount);
				treatRoad.getTreatBehavior(bh);
				previewArr=treatRoad.getRoadArr();						
			}else{
				trace("please draw in the board, then you can treat the data !!!\n");
			}			
			return previewArr;
		}
		private function transformData():Array
		{
			var adapter:PointToDistance=new PointToDistance();
			var arr:Array=adapter.trans(previewArr);
			return arr;
		}
		private function startHandler(evt:MouseEvent):void
		{
			if(evt.currentTarget.label=="startDraw")evt.currentTarget.label="redraw";
			__previewButt.enabled=true;
			__ballMoveButt.enabled=true;
			__getButt.enabled=true;
			redrawState();//回到绘图状态；
			//draw
		}
		private function previewHandler(evt:MouseEvent):void
		{
			if(drawRoad.getRoadArr().length>0)
			{
				previewArr=treatData();
				drawPreviewCurve();
				while(ballList[0].pos>=previewArr.length-1){
					ballSpr.removeChild(ballList.shift());	
				}
			}else{
				trace("please draw the road before you preview the end result!!!");
			}
		}
		private function moveHandler(evt:MouseEvent):void
		{
			if(__ballMoveButt.label=="ballMove"){
				ballSpr=new Sprite();
				drawBoard.addChildAt(ballSpr,1);
				ballList=new Array();
				if(drawRoad.getRoadArr()!=null&&drawRoad.getRoadArr().length>0)
				{
					previewArr=treatData();
					drawPreviewCurve();
					stage.addEventListener(Event.ENTER_FRAME,frameHandler);
				}else{
					trace("please draw the road before you test the ball move!!");
				}
			}else{
				drawBoard.removeChild(ballSpr);
				stage.removeEventListener(Event.ENTER_FRAME,frameHandler);
			}
			__ballMoveButt.label=(__ballMoveButt.label=="ballMove"?"removeBall":"ballMove");
		}
		private function getHandler(evt:MouseEvent):void
		{
			if(drawRoad.getRoadArr()!=null&&drawRoad.getRoadArr().length>0){
				previewArr=treatData();
				resultArr=transformData();
				drawPreviewCurve();				
				__resultText.text="private var oriX:Number = "+(previewArr[0].x-backLoader.x)+"\n"
				+"private var oriY:Number = "+(previewArr[0].y-backLoader.y)+"\n"
				+"private var posX:Array = ["+resultArr[0]+"];"+"\n"+"private var posY:Array = ["+resultArr[1]+"];\n";
				//切换到显示数据的场景
				drawSpr.visible=false;
				dataSpr.visible=true;
				if(stage.hasEventListener(Event.ENTER_FRAME))stage.removeEventListener(Event.ENTER_FRAME,frameHandler);
			}else{
				trace("please draw the road before you get the road data!!");
			}			
		}
		private function backHandler(evt:MouseEvent):void
		{
			drawSpr.visible=true;
			dataSpr.visible=false;	
		}
		private function frameHandler(evt:Event):void
		{
			if(ballList.length==0){
				var ball:TestBall=new TestBall();
				ball.width=ballD;
				ball.height=ballD;
				ballList.push(ball);
				ball.pos=0;
				ball.x=previewArr[ball.pos].x;
				ball.y=previewArr[ball.pos].y;
				ballSpr.addChild(ball);				
			}else{
				for(var i:uint=0;i<ballList.length;i++){
					ballList[i].pos++;
					ballList[i].x=previewArr[ballList[i].pos].x;
					ballList[i].y=previewArr[ballList[i].pos].y;				
				}
				if(ballList[ballList.length-1].pos==divideCount){
					var tempBall:TestBall=new TestBall();
					tempBall.width=ballD;
					tempBall.height=ballD;
					ballList.push(tempBall);
					tempBall.pos=0;
					tempBall.x=previewArr[tempBall.pos].x;
					tempBall.y=previewArr[tempBall.pos].y;
					ballSpr.addChild(tempBall);
				}
				if(ballList[0].pos==previewArr.length-1){
					ballSpr.removeChild(ballList.shift());
				}
			}
		}
		private function oriChangeHandler(evt:ColorPickerEvent):void{
			oriColor=evt.target.selectedColor;
			if(drawRoad!=null){
				drawRoad.color=oriColor;
				if(drawRoad.getRoadArr().length>0){
				drawOriCurve();
				}
			}else{
				
			}
		}
		private function previewChangeHandler(evt:ColorPickerEvent):void{
			previewColor=evt.target.selectedColor;
			if(previewArr.length>0){
				drawPreviewCurve();
			}else{
				
			}
		}
		private function enterHandler(evt:MouseEvent):void{
			adapteImg();
		}
		private function redrawState():void
		{
			getBackGround();
			try{
				drawBoard.removeChild(drawRoad);
			}catch(err:Error){
				
			}			
			drawRoad=new DrawCurve(drawBoard);
			drawBoard.addChild(drawRoad);
			drawRoad.color=__oriColorCP.selectedColor;
			resultCurve.graphics.clear();
			try{
				drawBoard.removeChild(ballSpr);
			}catch(err:Error){
				
			}
			ballSpr=new Sprite();
			drawBoard.addChildAt(ballSpr,1);
			
			previewArr=new Array();
			resultArr=new Array();
			
			if(stage.hasEventListener(Event.ENTER_FRAME))stage.removeEventListener(Event.ENTER_FRAME,frameHandler);
			
			__ballMoveButt.label="ballMove";
		}
		private function getBackGround():void
		{
			drawBoard.removeChild(backLoader);
			backLoader=new Loader();
			drawBoard.addChildAt(backLoader,0);
			var url:String=String(__bgLink.text);
			var request:URLRequest=new URLRequest(url);
			backLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler);
			backLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,ioErrHandler);
			backLoader.load(request);		
		}
		private function completeHandler(evt:Event):void
		{
			var lf:LoaderInfo=LoaderInfo(evt.target);	
			adapteImg();
		}
		private function ioErrHandler(evt:IOErrorEvent):void
		{
			trace("no img,so use default bg!\n");			
		}
		private function drawPreviewCurve():void{
			var gr:Graphics=resultCurve.graphics;
			gr.clear();
			gr.lineStyle(8,previewColor,.05);
			for(var i:uint=0;i<previewArr.length-1;i++)
			{
				gr.moveTo(previewArr[i].x,previewArr[i].y);
				gr.lineTo(previewArr[i+1].x,previewArr[i+1].y);
			}
		}
		private function drawOriCurve():void{
			drawRoad.color=oriColor;
			drawRoad.draw();
		}
		private function adapteImg():void{
			imgWidth=Number(__imgWidth.text);
			imgHeight=Number(__imgHeight.text);
			if(imgWidth<=1e-6){
				imgWidth=1000;
			}
			if(imgHeight<=1e-6){
				imgHeight=760;
			}
			backLoader.width=imgWidth;
			backLoader.height=imgHeight;
			backLoader.x=(1000-backLoader.width)/2;
			backLoader.y=(760-backLoader.height)/2;
		}
	}
}